import { commonSysApi, indexApi } from '@/api/api'

const getDefaultState = () => {
  return {
    topCate: [],
    homeInfo: null,
    commonSys: []
  }
}

const state = getDefaultState()

const mutations = {
  SET_HOME: (state, data) => {
    state.homeInfo = data
    state.topCate = data.index
  },
  SET_COMMON_SYS: (state, sys) => {
    state.commonSys = sys
  }
}

const actions = {
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      Promise.all([indexApiPromise, commonSysApiPromise])
        .then(resList => {
          const res0 = resList[0]
          const res1 = resList[1]
          if (res0.errno === 0 && res1.errno === 0) {
            commit('SET_HOME', res0.data)
            commit('SET_COMMON_SYS', res1.data)
            resolve()
          } else {
            reject()
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

const indexApiPromise = new Promise(resolve => {
  indexApi().then(res => {
    resolve(res)
  })
})

const commonSysApiPromise = new Promise(resolve => {
  commonSysApi().then(res => {
    resolve(res)
  })
})

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
